import { useCallback, useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { getCaseDetailRequest, updateCaseRequest } from './ajax'
import { awaitWrap, strToNum } from '@src/assets/js/tool'
import PageLoading from '@components/pageLoading'
import PageEmpty from '@components/pageEmpty'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { refreshCaseListVersion, setCaseDetail } from '@src/redux/reducers/cases'
import Person from './components/person'
import Accord from './components/accord'
import ApplyDoc from './components/applyDoc'
import Claim from './components/claim'
import Reason from './components/reason'
import CauseAction from './components/causeAction'
import Evidence from './components/evidence'
import { Button, Dialog, Toast } from 'antd-mobile'
import { pop, setList } from '@src/redux/reducers/pages'
import uuid from 'uuid'


async function initCase (id, setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseDetailRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setData(formatInitData(d))
  }
}

// 格式化争议金额
function formatInitData (d) {
  const { claim } = d
  const { items } = claim
  claim.dispute_amount = 0
  claim.fee_acceptance = 0
  claim.fee_processing = 0
  items.forEach(item => {
    if (strToNum(item.dispute_amount)) {
      claim.dispute_amount += strToNum(item.dispute_amount)
    }
    if (strToNum(item.fee_acceptance)) {
      claim.fee_acceptance += strToNum(item.fee_acceptance)
    }
    if (strToNum(item.fee_processing)) {
      claim.fee_processing += strToNum(item.fee_processing)
    }
  })
  return d
}

async function sumbitHandle (userInfo, id, dispatch) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(updateCaseRequest(id, {
    status: '待审核',
    submittal: userInfo.realname,
    submittalid: userInfo.id,
    submit_datetime: Math.floor(Date.now() / 1000),
  })) 
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(setList([{ element: 'admin', id: uuid() }, { element: 'caseDetail', id: uuid(), meta: { id } }]))
  }
}

async function delHandle (id, dispatch) {
  Toast.show({ content: '删除中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(updateCaseRequest(id, { status: '已作废' })) 
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '删除成功', icon: 'success' })
    dispatch(pop())
    dispatch(refreshCaseListVersion())
  }
}

// 是否为空
function isEmpty (s) {
  const t = typeof s
  if (t === 'string') {
    return s === ''
  } else if (t === 'number') {
    return s === 0
  } else if (s instanceof Array) {
    return s.length === 0
  }
  return s === undefined || s === null
}

// 验证当事人信息是否完善
function validateParty (data) {
  const keys = ['tag', 'name', 'license_type', 'license', 'address_type', 'address']
  for (let i = 0; i < keys.length; i++) {
    const k = keys[i]
    if (isEmpty(data[k])) {
      return false
    }
  }
  if (data.subject_type === '自然人') {
    // if (isEmpty(data.area) || isEmpty(data.fileid) || isEmpty(data.fileid1)) {
    if (isEmpty(data.area)) {
      return false
    }
  }
  return true
}

// 验证代理人信息是否完善
function validateAgent (data) {
  const keys = ['name', 'license_type', 'license', 'structure', 'address']
  for (let i = 0; i < keys.length; i++) {
    const k = keys[i]
    if (isEmpty(data[k])) {
      return false
    }
  }
  if (data.party === null || data.party.length === 0) {
    return false
  }
  return true
}


function validateCase (c) {
  if (c.applicants.length === 0) {
    Toast.show({ content: '申请人不能为空' })
    return false
  } else if (!c.applicants.every(li => validateParty(li))) {
    Toast.show({ content: '申请人信息不完善' })
    return false
  } else if (!c.applicant_agents.every(li => validateAgent(li))) {
    Toast.show({ content: '代理人信息不完善' })
    return false
  } else if (c.respondents.length === 0) {
    Toast.show({ content: '被申请人不能为空' })
    return false
  } else if (!c.respondents.every(li => validateParty(li))) {
    Toast.show({ content: '被申请人信息不完善' })
    return false
  } else if (c.claim === undefined || c.claim === null || !(c.claim.items instanceof Array) || c.claim.items.length === 0) {
    Toast.show({ content: '仲裁请求不能为空' })
    return false
  }
  return true
}

function Main ({ meta = {} }) {
  const data = useAppSelector(state => state.cases.caseDetail)
  const version = useAppSelector(state => state.cases.caseEditVersion)
  const dispatch = useAppDispatch()
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const [loading, setLoading] = useState(true)
  const errRemark = useMemo(() => {
    return data && typeof data.audit_complete_remark === 'string' ? data.audit_complete_remark : ''
  }, [data])
  const setData = useCallback(v => {
    dispatch(setCaseDetail(v))
  }, [dispatch])
  const id = useMemo(() => {
    return meta.id || ''
  }, [meta])
  useEffect(() => {
    if (id) {
      setData(null)
      initCase(id, setData, setLoading)
    }
  }, [id, setData, version])
  if (loading) {
    return (
      <PageComponent title='仲裁申请书'>
        <PageLoading />
      </PageComponent>
    )
  }
  if (!data) {
    return (
      <PageComponent title='仲裁申请书'>
        <div className={style.container}>
          <PageEmpty />
        </div>
      </PageComponent>
    )
  }
  return (
    <PageComponent title='仲裁申请书'>
      <div className={style.container}>
        {
          errRemark && (
            <div className={style.notice}>
              <div className={style['notice-inner']}>
                <div className={style['notice-title']}>审核不通过</div>
                <div className={style['notice-text']}>{errRemark}</div>
              </div>
            </div>
          )
        }
        <Person data={data.applicants} caseid={data.id} apply />
        <Person data={data.applicant_agents} caseid={data.id}  apply agent />
        <Person data={data.respondents} caseid={data.id}  />
        <Accord data={data} />
        <ApplyDoc data={data} />
        <Claim data={data} caseid={data.id} />
        <Reason data={data} caseid={data.id} />
        <CauseAction data={data} caseid={data.id} />
        <Evidence data={data.evidence || []} caseid={data.id} />
        <div className={style.btns}>
          <Button color='primary' block onClick={() => {
            if (!validateCase(data)) {
              return undefined
            }
            Dialog.confirm({
              content: '您确定提交审核吗？',
              onConfirm: () => {
                sumbitHandle(userInfo, data.id, dispatch)
              }
            })
          }}>提交审核</Button>
          <Button className={style.del} block onClick={() => {
            Dialog.confirm({
              content: '您确定删除案件吗？',
              onConfirm: () => {
                delHandle(data.id, dispatch)
              }
            })
          }}>删除案件</Button>
        </div>
      </div>
    </PageComponent>
  )
}

export default Main
